using MediatR;
using ProduceBasicData.Api.Application.Command.Material.Craft;
using ProduceBasicData.Api.DTO;
using ProduceBasicData.Domain.Inventories;
using ProduceBasicData.ErrorCode;
using ProduceBasicData.Infrastructure.Interface;

namespace ProduceBasicData.Api.Application.Handler.Material.Craft
{
    /// <summary>
    /// 工艺路线选择处理类（用于下拉框）
    /// </summary>
    public class GetCraftSelectHandler : IRequestHandler<GetCraftSelectCommand, ApiResult<List<CraftSelectDTO>>>
    {
        private readonly IBaseRespository<CraftModel> craftRepository;

        public GetCraftSelectHandler(IBaseRespository<CraftModel> craftRepository)
        {
            this.craftRepository = craftRepository;
        }

        public Task<ApiResult<List<CraftSelectDTO>>> Handle(GetCraftSelectCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<List<CraftSelectDTO>>();

            try
            {
                // 获取工艺路线数据
                var query = craftRepository.GetAll().Where(x => !x.Isdel);

                // 如果只获取启用的工艺路线（通过状态判断）
                if (request.OnlyEnabled)
                {
                    query = query.Where(x => x.CraftStatus == "启用" || x.CraftStatus == "正常");
                }

                // 映射到选择DTO
                var crafts = query
                    .OrderBy(x => x.CraftName)
                    .Select(x => new CraftSelectDTO
                    {
                        Id = x.Id,
                        CraftName = x.CraftName,
                        CraftDesc = x.CraftDesc
                    })
                    .ToList();

                result.Data = crafts;
                result.Code = ApiEnum.Success;
                result.Msg = "工艺路线选择列表获取成功";
            }
            catch (Exception ex)
            {
                result.Code = ApiEnum.Failed;
                result.Msg = $"工艺路线选择列表获取失败：{ex.Message}";
            }

            return Task.FromResult(result);
        }
    }
}
